import io

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.core.paginator import Paginator

from myapp.models import Book, Cseqdata
from django.core import serializers
import json
import pandas as pd


# Create your views here.
@require_http_methods(["POST"])
def import_data(request):
    if request.method == 'POST':
        response = {}
        if request.FILES['file']:
            excel_file = request.FILES['file']
            file_buffer = io.BytesIO(excel_file.read())
            try:
                df = pd.read_csv(file_buffer, encoding='ISO-8859-1')
                for index, row in df.iterrows():
                    obj = Cseqdata(group=row['group'], accession=row['accession'], title=row['title'],
                                   cell_line=row['cell_line'],
                                   technology=row['technology'], antibody=row['antibody'], mark_for_delete=False)
                    obj.save()
            except Exception as e:
                response['msg'] = str(e)
                response['error_num'] = 1
            response['success'] = True
            response['error_num'] = 0
        else:
            response['success'] = False
        return JsonResponse(response)


@require_http_methods(["GET"])
def show_data(request):
    if request.method == 'GET':
        response = {}
        try:
            data = Cseqdata.objects.filter()
            response['list'] = json.loads(serializers.serialize("json", data))
            response['success'] = True
            response['total'] = len(response['list'])
        except Exception as e:
            response['msg'] = str(e)
            response['error_num'] = 1

        return JsonResponse(response)


@require_http_methods(["POST"])
def get_data(request):
    if request.method == 'POST':
        response = {}
        try:
            body = json.loads(request.body)

            page = body['page']
            page_size = body['page_size']
            try:
                params = body['params']
            except KeyError:
                params = None
            if params is not None:
                if params['group'] or params['accession']:
                    all_data = Cseqdata.objects.filter(group=params['group'], accession=params['accession'])
            else:
                all_data = Cseqdata.objects.filter()
            # 调用默认分页实现 Paginator
            paginator = Paginator(all_data, per_page=page_size)
            total = paginator.count
            # 获取指定页的数据，结果为queryset
            data = paginator.get_page(page)
            response['list'] = json.loads(serializers.serialize("json", data))
            response['success'] = True
            response['page_size'] = page_size
            response['page'] = page
            response['total'] = total
        except Exception as e:
            response['msg'] = str(e)
            response['error_num'] = 1
            response['success'] = False

        return JsonResponse(response)


@require_http_methods(["POST"])
def get_options(request):
    if request.method == 'POST':
        response = {}
        try:
            body = json.loads(request.body)
            option = body['option']
            results = list(Cseqdata.objects.values_list(option, flat=True).distinct())
            res = []
            for i in range(len(results)):
                res.append({'label': results[i], 'value': results[i]})
            response['data'] = res
        except Exception as e:
            response['msg'] = str(e)
        return JsonResponse(response)
